package com.capgemini.mulefocus.transformer;

import java.util.ArrayList;
import java.util.List;

import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;
import org.mule.transformer.types.DataTypeFactory;

import com.capgemini.mulefocus.data.Tweet;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

public class TwitterSearchToOutputFormat extends AbstractTransformer {

	
	

	public TwitterSearchToOutputFormat() {
		super();
		 this.registerSourceType(DataTypeFactory.create(String.class));
	     this.setReturnDataType(DataTypeFactory.create(List.class));
	}

	@Override
	protected Object doTransform(Object src, String enc) throws TransformerException {
		
		String source = (String) src;
		List<DBObject> tweetList = splitResults(source);
		return tweetList;
	}

	private List<DBObject> splitResults(String source) {
		List<DBObject> tweetList = new ArrayList<DBObject>();
		int startOfTweets = source.indexOf("[") + 1;
		int endOfTweets = source.indexOf("]");
		String tweets = source.substring(startOfTweets, endOfTweets);
		
		int counter = 0; 
		while(tweets.indexOf("},{") >= 0){
			String tweetString = tweets.substring(0, tweets.indexOf("},{") + 2);
			tweets = tweets.substring(tweets.indexOf("},{") + 2);
			
			DBObject tweet = (DBObject) JSON.parse(tweetString);
			tweetList.add(tweet);
			
			if(counter > 500){
				throw new IndexOutOfBoundsException();
			}
			counter++;
		}
		return tweetList;
	}

}
